package com.example.ch06jdbcuserdetailsservice.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;

import javax.sql.DataSource;

/**
 * @description:
 * @author:ScorpioWang
 * @date:2021-11-02-09-32
 */
@Configuration
public class ApplicationConfig {
    //通过spring容器注入DataSource
    @Autowired
    private DataSource dataSource;

    //创建PasswordEncoder对象
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //创建JdbcUserDetailsService对象
    @Bean(name = "jdbcUserDetailsService")
    public UserDetailsService jdbcUserDetailsService() {
        System.out.println("dataSource==="+dataSource);

        PasswordEncoder encoder = passwordEncoder();

        //初始数据源DataSource
        JdbcUserDetailsManager manager = new JdbcUserDetailsManager(dataSource);
        //如果数据库中已经存在账号就不添加
        if(!manager.userExists("admin")){
            manager.createUser(User.withUsername("admin")
                    .password(encoder.encode("admin"))
                    .roles("ADMIN", "USER", "MANAGER").build());
        }

        if (!manager.userExists("common")){
            manager.createUser(User.withUsername("common")
                    .password(encoder.encode("common"))
                    .roles("USER").build());
        }

        if(!manager.userExists("wang")){
            manager.createUser(User.withUsername("wang")
                    .password(encoder.encode("wang"))
                    .roles("USER", "NORMAL").build());
        }

        return manager;
    }
}
